<?php

/**
 * User: nickbai
 * Date: 2017/10/23 13:33
 * Email: 1902822973@qq.com
 */

namespace app\admin\controller;

use think\Log;
use app\index\model\User;
use Illuminate\Support\Arr;
use app\admin\model\Service;
use app\wechat\model\OauthUser;

class Users extends Base
{
    // 客服列表
    public function index()
    {
        if (request()->isAjax()) {
            $input = request()->request();
            $query = Service::with('superior')->order('id', 'desc');
            $count_query = new Service;
            $condition = [];
            if (!empty($input['user_name'])) {
                $condition['user_name'] = ['like', '%' . $input['user_name'] . '%'];
            }
            if (!empty($input['service_name'])) {
                $condition['service_name'] = ['like', '%' . $input['service_name'] . '%'];
            }
            if (!empty($input['role'])) {
                $condition['role'] = intval($input['role']);
            }
            if (!empty($input['superior_name'])) {
                $q = fn ($query) => $query
                    ->table(['ws_services' => 'superior'])
                    ->field('1')
                    ->where('`ws_services`.`superior_id` = `superior`.`id`')
                    ->where('superior.service_name', 'like', '%' . $input['superior_name'] . '%');

                $query->whereExists($q);
                $count_query->whereExists($q);
            }

            $limit = $input['pageSize'];
            $offset = ($input['pageNumber'] - 1) * $limit;
            $count = $count_query->where($condition)->count();
            $result = $query->where($condition)->limit($offset, $limit)->select()->map(function ($service) {
                // 优化显示头像
                $service['user_avatar'] = '<img src="' . $service['user_avatar'] . '" width="40px" height="40px">';

                // 优化显示状态
                if (1 == $service['status']) {
                    $service['status'] = '<span class="label label-primary">启用</span>';
                } else {
                    $service['status'] = '<span class="label label-danger">禁用</span>';
                }

                // 查询分组
                $service['role'] = Service::ROLES_MAP[$service->role];
                // 优化显示在线状态
                if (1 == $service['online']) {
                    $service['online'] = '<span class="label label-primary">在线</span>';
                } else {
                    $service['online'] = '<span class="label label-danger">离线</span>';
                }
                // 生成操作按钮
                $service['operate'] = $this->makeBtn($service['id']);
                $service['superior_name'] = $service->superior->service_name ?? '';
                return $service;
            });

            return json([
                'total' => $count,
                'rows' =>  $result->toArray()
            ]);
        }

        $this->assign([
            'role' => Service::ROLES_MAP
        ]);

        return $this->fetch();
    }

    // 添加客服
    public function addUser()
    {
        if (request()->isPost()) {
            $param = input('post.');
            unset($param['file']); // 删除layui头像上传隐藏字段
            $wechat_user = null;

            if ($param['openid']) {
                $wechat_user = OauthUser::where('openid', $param['openid'])->find();
                if (!$wechat_user) {
                    return json(['code' => -1, 'data' => '', 'msg' => 'openid无效']);
                }
            }
            // 检测头像
            if (empty($param['user_avatar']) && $wechat_user) {
                $param['user_avatar'] = $wechat_user->headimgurl;
            }

            if (empty($param['role'])) {
                return json(['code' => -4, 'data' => '', 'msg' => '请选择类型']);
            }

            // $has = db('services')->field('id')->where('role', $param['role'])->where('service_name', $param['service_name'])->find();
            // if (!empty($has)) {
            //     return json(['code' => -2, 'data' => '', 'msg' => '该客服已经存在']);
            // }

            $param['user_pwd'] = md5(($param['user_pwd'] ?? '123456') . config('salt'));
            $param['online'] = 2; // 离线状态

            try {
                $service = new Service($param);
                $result = $service->allowField(true)->save();

                if ($result && $param['user_id']) {
                    $user = User::find($param['user_id']);
                    $user && $user->delete();
                }
            } catch (\Exception $e) {
                return json(['code' => -3, 'data' => '', 'msg' => $e->getMessage()]);
            }

            return json(['code' => 1, 'data' => '', 'msg' => '添加成功']);
        }

        $selected_role = null;
        $superior = [];
        $role_map = [
            'service' => Service::ROLE_DEPARTMENT,
            'department' => Service::ROLE_MARKET,
            'market' => Service::ROLE_SHOP,
        ];
        $user = User::find(intval(input('param.id/d')));
        if (request()->has('role', 'get') && ($selected_role = $role_map[request()->get('role')] ?? null)) {
            $superior = Service::where('role', $selected_role + 1)->column("CONCAT(service_name,'-', user_name)", 'id');
        }
        $this->assign([
            'role' => Arr::except(Service::ROLES_MAP, Service::ROLE_SERVICE),
            'status' => config('kf_status'),
            'superior_id' => request()->get('superior_id', 0),
            'selected_role' => $selected_role,
            'superior' => $superior,
            'user_id' => $user->id ?? 0,
            'user_openid' => $user->openid ?? '',
            'user_name' => $user->name ?? '',
            'user_avatar' => $user->headimgurl ?? '',
            'user_mobile' => $user->mobile ?? '',
        ]);

        return $this->fetch();
    }

    // 编辑客服
    public function editUser()
    {
        if (request()->isAjax()) {
            $param = input('post.');
            unset($param['file']); // 删除layui头像上传隐藏字段

            /**
             * @var Service
             */
            $service = Service::find($param['id'] ?? 0);
            if (empty($service)) {
                return json(['code' => -1, 'data' => '', 'msg' => '客服不存在']);
            }
            if (empty($param['role'])) {
                return json(['code' => -4, 'data' => '', 'msg' => '请选择客服类型']);
            }
            $service->role = $param['role'];
            // // 检测用户修改的用户名是否重复
            // $has = db('services')->where('role', $param['role'])->where('service_name', $param['service_name'])->where('id', '<>', $param['id'])->find();
            // if (!empty($has)) {
            //     return json(['code' => -1, 'data' => '', 'msg' => '该客服已经存在']);
            // }
            $service->service_name = trim($param['service_name']);
            $service->user_name = trim($param['user_name']);
            $service->user_avatar = $param['user_avatar'];
            $service->superior_id = $param['superior_id'] ?? 0;
            $service->status = $param['status'];

            if (isset($param['mobile']) && is_numeric($param['mobile'])) {
                $service->mobile = $param['mobile'];
            }

            if (empty($param['openid'])) {
                // return json(['code' => -1, 'data' => '', 'msg' => '请设置openid']);
                $service->openid = null;
            } else {
                if ($param['openid'] != $service->openid) {
                    $wechat_user = OauthUser::where('openid', $param['openid'])->find();
                    if (!$wechat_user) {
                        return json(['code' => -1, 'data' => '', 'msg' => 'openid无效']);
                    }
                    $service->openid = $param['openid'];
                }
            }

            // 修改用户密码
            if (!empty($param['user_pwd'])) {
                $service->user_pwd = md5($param['user_pwd'] . config('salt'));
            }
            try {
                $service->save();
            } catch (\Exception $e) {
                return json(['code' => -2, 'data' => '', 'msg' => $e->getMessage()]);
            }

            return json(['code' => 1, 'data' => '/admin/users/index.html', 'msg' => '编辑成功']);
        }

        $id = input('param.id/d');
        $info = db('services')->where('id', $id)->find();

        $this->assign([
            'info' => $info,
            'status' => config('kf_status'),
            'role' => Arr::except(Service::ROLES_MAP, Service::ROLE_SERVICE)
        ]);
        return $this->fetch();
    }
    // 编辑客服
    public function editShop()
    {
        if (request()->isAjax()) {
            try {
                $param = input('post.');
                unset($param['file']); // 删除layui头像上传隐藏字段
                // $param['role'] = Service::ROLE_SHOP;
                /**
                 * @var Service
                 */
                $shop = Service::find($param['id'] ?? 0);
                if (empty($shop)) {
                    return json(['code' => -1, 'data' => '', 'msg' => '门店不存在']);
                }
                // 检测用户修改的用户名是否重复
                // if (db('services')->where('role', $param['role'])->where('service_name', $param['service_name'])->where('id', '<>', $param['id'])->value('id')) {
                //     return json(['code' => -1, 'data' => '', 'msg' => '该门店已经存在']);
                // }

                // $shop->role = $param['role'];
                $shop->service_name = trim($param['service_name']);
                $shop->user_name = trim($param['user_name']);
                $shop->mobile = $param['mobile'];
                $shop->user_avatar = $param['user_avatar'];
                if ($shop->superior_id != $param['superior_id']) {
                    $shop->superior_id = $param['superior_id'];
                    $m = Service::find($param['superior_id']);
                    $p = $m->superior()->find();
                    $s = $p->superior()->find();
                    User::where('shop_id', $shop->id)->update([
                        'service_id' => $s->id,
                        'department_id' => $p->id,
                        'market_id' => $m->id
                    ]);
                }

                if (empty($param['openid'])) {
                    // return json(['code' => -1, 'data' => '', 'msg' => '请设置openid']);
                    $shop->openid = null;
                } else {
                    if ($param['openid'] != $shop->openid) {
                        $wechat_user = OauthUser::where('openid', $param['openid'])->find();
                        if (!$wechat_user) {
                            return json(['code' => -1, 'data' => '', 'msg' => 'openid无效']);
                        }
                        $shop->openid = $param['openid'];
                    }
                }

                $shop->save();
            } catch (\Exception $e) {
                Log::error('修改门店失败:'.$e);
                return json(['code' => -2, 'data' => '', 'msg' => '修改门店失败']);
            }

            return json(['code' => 1, 'data' => '/admin/users/editShop/id/' . $shop->id, 'msg' => '编辑成功']);
        }

        $id = input('param.id/d');
        $shop = Service::find($id);
        // $market = $shop->children()->find();
        $this->assign([
            'shop' => $shop,
            // 'market' => $market,
            'status' => config('kf_status')
        ]);
        return $this->fetch();
    }

    // 删除客服
    public function delUser()
    {
        if (request()->isAjax()) {
            $id = input('param.id/d');

            try {
                db('services')->where('id', $id)->delete();
            } catch (\Exception $e) {
                return json(['code' => -1, 'data' => '', 'msg' => $e->getMessage()]);
            }

            return json(['code' => 1, 'data' => '', 'msg' => '删除客服成功']);
        }
    }

    public function superior()
    {
        if (request()->isAjax()) {
            $role = request()->get('role', 0);
            if ($role == 0) {
                return Service::where('role', '>', 1)->column("CONCAT(service_name,'-', user_name)", 'id');
            }
            if ($role === Service::ROLE_SERVICE) {
                return json([]);
            }
            return Service::where('role', $role + 1)->column("CONCAT(service_name,'-', user_name)", 'id');
        }
        return 'success';
    }
    public function children()
    {
        if (request()->isAjax()) {
            $id = request()->get('id', 0);
            $service = Service::find($id);
            return Service::where('superior_id', $id)->where('role', $service->role - 1)->column("CONCAT(service_name,'-', user_name)", 'id');
        }
        return 'success';
    }

    // 上传客服头像
    public function upAvatar()
    {
        if (request()->isAjax()) {
            $file = request()->file('file');
            if (!empty($file)) {
                // 移动到框架应用根目录/public/uploads/ 目录下
                $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
                if ($info) {
                    $src = '/uploads' . '/' . date('Ymd') . '/' . $info->getFilename();
                    return json(['code' => 0, 'data' => ['src' => $src], 'msg' => 'ok']);
                } else {
                    // 上传失败获取错误信息
                    return json(['code' => -1, 'data' => '', 'msg' => $file->getError()]);
                }
            }
        }
    }

    // 生成按钮
    private function makeBtn($id)
    {
        $operate = '<a href="' . url('users/edituser', ['id' => $id]) . '">';
        $operate .= '<button type="button" class="btn btn-primary btn-sm"><i class="fa fa-paste"></i> 编辑</button></a> ';

        $operate .= '<a href="javascript:userDel(' . $id . ')"><button type="button" class="btn btn-danger btn-sm">';
        $operate .= '<i class="fa fa-trash-o"></i> 删除</button></a> ';


        //$operate .= '<a href="javascript:;">';
        //$operate .= '<button type="button" class="btn btn-info btn-sm"><i class="fa fa-institution"></i> 详情</button></a>';

        return $operate;
    }
}
